// v8-compile-cache模块用于缓存 V8 JavaScript 编译结果，以提高应用程序的启动速度和性能。它会在应用程序启动时自动缓存编译结果，无需额外的步骤或配置。
// 此模块需要在首行引入，仅适用于主进程，对于渲染进程则不起作用。
require('v8-compile-cache');
// 生成v8-compile-cache文件会保存到【C:\Users\UserName\AppData\Local\Temp\v8-compile-cache\x64】，启动后退出才生成。
import fs from 'fs';
import tmp from 'tmp';
import {
    app,
    BrowserWindow,
    clipboard,
    dialog,
    globalShortcut,
    ipcMain,
    Menu,
    MenuItem,
    nativeImage as NativeImage,
    powerMonitor,
    protocol,
    session,
    shell,
    Tray,
    screen,
    Notification,
    BrowserView,
    crashReporter,
    netLog,
} from 'electron';

import windowStateKeeper from 'electron-window-state';
import i18n from 'i18n';
import proto from '../marswrapper.node';

import pkg from '../package.json';
import Badge from 'electron-windows-badge';
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
// import {Registry} from "rage-edit";
import axios from "axios";

import {init as initProtoMain} from "./wfc/proto/proto_main";

var path = require('path');
const qs = require ("querystring");
const os = require("os");

const ref = require('ref-napi');

// Scheme must be registered before the app is ready
import logger from './log_main';
console.log = logger.log;
console.info = logger.info;
console.warn = logger.warn;
console.error = logger.error;
console.debug = logger.debug;

// 自动更新
const {autoUpdater} = require("electron-updater");
autoUpdater.autoDownload = false; // 关闭自动更新
autoUpdater.autoInstallOnAppQuit = false; // APP退出的时候自动安装（目前为true时只卸载，没有再安装，可能是bug，暂且不用）

// 增量更新
const DeltaUpdater = require("./electron-delta/updater");
const deltaUpdater = new DeltaUpdater({
    logger,
    autoUpdater: autoUpdater,
    // hostURL: "you can mention the host url or it's computed from app-update.yml file"
    // 此处不需要指定
    // hostURL: "http://localhost:5000/",
});

// 此处isQuitAndInstall相关逻辑无效，在beforeExitAppToInstall中实现，暂且残留
function beforeExitApp(isQuitAndInstall=false, isFromLoginPage=false) {
    if(isQuitAndInstall){
        if(!!settingWindow && settingWindow.isVisible()){
            settingWindow.close();
        }
    }
    mainWindow && mainWindow.hide(); // 系统托盘退出时会短暂呈现拉宽的登录页面，需点击退出时直接隐藏掉
    // 解除阻止应用被暂停模式
    powerSaveBlocker.stop(powerSaveBlockerId);
    if(isFromLoginPage){
        // 来自login页面
        forceQuit = true;
        // autoUpdater.quitAndInstall();
        deltaUpdater.quitAndInstall();
        // doExitApp(true);
    }else{
        // 来自setting页面或login页面Alt+Q退出
        if(!isLoginFlag){
            forceQuit = true;
            // login页面Alt+Q退出
            mainWindow && mainWindow.close();
        }else{
            // 来自setting页面
            // store中check各会话的草稿，刷新indexeddb信息
            mainWindow && mainWindow.webContents.send('refreshIndexeddbInfo', {flag: "exitapp", isQuitAndInstall: isQuitAndInstall});
        }
    }
}

function beforeExitAppToInstall(isQuitAndInstall=false, isFromLoginPage=false) {
    if(isQuitAndInstall){
        if(!!settingWindow && settingWindow.isVisible()){
            settingWindow.close();
        }
    }
    mainWindow && mainWindow.hide(); // 系统托盘退出时会短暂呈现拉宽的登录页面，需点击退出时直接隐藏掉
    // 解除阻止应用被暂停模式
    powerSaveBlocker.stop(powerSaveBlockerId);
    if(isFromLoginPage){
        // 来自login页面
        deltaUpdater.quitAndInstall((isDelta) => {
            doExitApp(true, isDelta);
        });
    }else{
        // 来自setting页面
        moadlBrowserWindow && moadlBrowserWindow.hide(); // 隐藏设置页面
        deltaUpdater.quitAndInstall((isDelta) => {
            // store中check各会话的草稿，刷新indexeddb信息
            mainWindow && mainWindow.webContents.send('refreshIndexeddbInfo', {flag: "exitapp", isQuitAndInstall: isQuitAndInstall, isDelta: isDelta});
        });
    }
}

function doExitApp(isQuitAndInstall=false, isDelta=false) {
    isFoceLogouted = true;
    // 杀掉QT截图工具yfscreenshot进程
    killYfScreenshotProcess();
    // 获取所有打开的window
    var allOpenBrowser = BrowserWindow.getAllWindows();
    console.log('******************************allOpenBrowserlength: ' + allOpenBrowser.length);
    for (var i = 0; i <allOpenBrowser.length;i++){
        console.log('******************************allOpenBrowser[' + i + '].webContents.id 窗口: ' + allOpenBrowser[i].webContents.id);
        // 清除mainWindow以外的所有窗口，否则进程会越来越多，不能关闭mainWindow，否则会出发设置为null操作导致后续报错
        if(allOpenBrowser[i].webContents.id != 1){
            console.log('******************************allOpenBrowser[' + i + '].webContents.id 窗口 = null: ' + allOpenBrowser[i].webContents.id);
            allOpenBrowser[i].close();
            // 清空为null要慎重，比如设置页面如果在此清为null，退出登录就会无效，窗体destroy后事件不能正常发送
            allOpenBrowser[i] = null;
        }
    }
    for(var x = 0; x < cacheBrowserWindow.length; x++){
        console.log('^^^^^^^^^^^^^^^^^^^^^^^^^^^^cacheBrowserWindow[' + x + '].webContents.id 窗口 = null: ' + cacheBrowserWindow[x].webContents.id);
        // cacheBrowserWindow[x].close();
        cacheBrowserWindow[x] = null;
    }
    for(var y = 0; y < cacheModalBrowserWindow.length; y++){
        console.log('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%cacheModalBrowserWindow[' + y + '].webContents.id 窗口 = null: ' + cacheModalBrowserWindow[y].webContents.id);
        // cacheModalBrowserWindow[y].close();
        cacheModalBrowserWindow[y] = null;
    }
    if(pdfPreviewWindow != null){
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&pdfPreviewWindow.webContents.id 窗口 = null: ' + pdfPreviewWindow.webContents.id);
        pdfPreviewWindow = null;
    }
    // if(allChildBrowserWindow != null){
    //     // allChildBrowserWindow.close();
    //     console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&allChildBrowserWindow.webContents.id 窗口 = null: ' + allChildBrowserWindow.webContents.id);
    //     allChildBrowserWindow = null;
    // }
    if(moadlBrowserWindow != null){
        // moadlBrowserWindow.close();
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&moadlBrowserWindow.webContents.id 窗口 = null: ' + moadlBrowserWindow.webContents.id);
        moadlBrowserWindow = null;
    }
    if(fileWindow != null){
        // fileWindow.close();
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&fileWindow.webContents.id 窗口 = null: ' + fileWindow.webContents.id);
        fileWindow = null;
    }
    if(workspaceWindow != null){
        // workspaceWindow.close();
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&workspaceWindow.webContents.id 窗口 = null: ' + workspaceWindow.webContents.id);
        workspaceWindow = null;
    }
    if(webBrowserWindow != null){
        // webBrowserWindow.close();
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&webBrowserWindow.webContents.id 窗口 = null: ' + webBrowserWindow.webContents.id);
        webBrowserWindow = null;
    }
    if(webBrowserModalWindow != null){
        // webBrowserModalWindow.close();
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&webBrowserModalWindow.webContents.id 窗口 = null: ' + webBrowserModalWindow.webContents.id);
        webBrowserModalWindow = null;
    }
    if(commonmodalWindow != null){
        // commonmodalWindow.close();
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&commonmodalWindow.webContents.id 窗口 = null: ' + commonmodalWindow.webContents.id);
        commonmodalWindow = null;
    }
    if(settingWindow != null){
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&settingWindow.webContents.id 窗口 = null: ' + settingWindow.webContents.id);
        settingWindow = null;
    }

    if(newMessageNoticeWin != null){
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&newMessageNoticeWin.webContents.id 窗口 = null: ' + newMessageNoticeWin.webContents.id);
        newMessageNoticeWin.close();
        // newMessageNoticeWin = null;
    }

    if(userCardBrowserWin != null){
        console.log('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&userCardBrowserWin.webContents.id 窗口 = null: ' + userCardBrowserWin.webContents.id);
        userCardBrowserWin.close();
        // userCardBrowserWin = null;
    }

    // var allOpenBrowser2 = BrowserWindow.getAllWindows();
    // console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@ allOpenBrowser2.length: ' + allOpenBrowser2.length);

    cacheBrowserWindow = [];
    cacheModalBrowserWindow = [];
    historyMessageWindowIds.clear();
    compositeMessageWindowIds.clear();
    separateWindowIds.clear();
    allHistoryMessageWinId = null;
    allImagePrewerWinId = null;
    imageEditWinId = null;
    videoPlayWinId = null;
    // currentWindowId = null;
    isLoginFlag = false;
    loginedTime = -1;
    // if(!isQuitAndInstall){
    //     exitApp();
    // }else{
    //     exitApp(true);
    //     // setTimeout(() => {
    //     //     autoUpdater.quitAndInstall();
    //     // }, 2000);
    // }
    exitApp(isQuitAndInstall, isDelta);
}

ipcMain.on("doExitApp", (event, args)=>{
    var isDelta = (args.isDelta==null || args.isDelta==undefined)? true : args.isDelta;
    doExitApp(args.isQuitAndInstall, isDelta);
});

ipcMain.on("check-for-update", (event, args)=>{
    // 检测是否有更新
    // autoUpdater.checkForUpdates();
    deltaUpdater.checkForUpdates();
});

ipcMain.on("exit-and-update", (event, args)=>{
    // // 杀掉QT截图工具yfscreenshot进程
    // killYfScreenshotProcess();
    // doExitApp(false);
    // beforeExitApp(true, args.isFromLoginPage);
    beforeExitAppToInstall(true, args.isFromLoginPage);
    // 安装更新
    // // https://github.com/electron-userland/electron-builder/issues/3402
    // setImmediate(() => {
    //     autoUpdater.quitAndInstall();
    // });
    // autoUpdater.quitAndInstall();
    // 怀疑以上处理已退出，再次退出导致Cannot read properties of null(reading 'focus')错误
    // exitApp();
});

ipcMain.on("yfscreenshot-checkStatus", (event, args)=>{
    // 先确认截图工具是否已启动，如果已启动则杀掉，否则将无法把IM句柄更新至已启动的截图工具中
    checkIfScreenshotIsRunning();
});

ipcMain.on("yfscreenshot-startup", (event, args)=>{
    // 启动截图工具yfscreenshot
    yfscreenshotWinId = 0;
    yfscreenshotProcessId = 0;
    yfscreenshotWinId_ImStart = 0;
    yfscreenshotProcessId_ImStart = 0;
    yfscreenshotStartup();
});

function checkIfScreenshotIsRunning(){
    // 先确认截图工具是否已启动，如果已启动则杀掉，否则将无法把IM句柄更新至已启动的截图工具中
    getScreenshotPidWinId();
    if(yfscreenshotWinId != 0 || yfscreenshotProcessId != 0){
        console.log("**********************kill已启动的截图工具前: " + yfscreenshotProcessId + "|" + yfscreenshotWinId);
        // 在主进程启动时会check并kill一次，在login时再check+kill时可能processId还不为0，但winId已经为0，所以再次kill会报错，经判断无影响
        killYfScreenshotProcess();
        console.log("**********************kill已启动的截图工具后: " + yfscreenshotProcessId + "|" + yfscreenshotWinId);
    }
    yfscreenshotWinId = 0;
    yfscreenshotProcessId = 0;
    yfscreenshotWinId_ImStart = 0;
    yfscreenshotProcessId_ImStart = 0;
}

function getScreenshotPidWinId(){
    try{
        var processId_winId = Buffer.alloc(32);
        processId_winId.type = ref.types.char;
        // processId_winId = require("./ReadCopyDataMsg").GetScreenshotWinId(yfscreenshotExeName);
        processId_winId = GetScreenshotWinId(yfscreenshotExeName);
        var str_actualWinId = ref.readCString(processId_winId, 0);
        console.log(str_actualWinId);
        yfscreenshotProcessId = str_actualWinId.split("|")[0];
        yfscreenshotWinId = str_actualWinId.split("|")[1];
        // 如果是首次由IM启动，则保存
        if(yfscreenshotProcessId_ImStart == 0){
            yfscreenshotProcessId_ImStart = yfscreenshotProcessId;
        }
        if(yfscreenshotWinId_ImStart == 0){
            yfscreenshotWinId_ImStart = yfscreenshotWinId;
        }
        console.log("getScreenshotPidWinId结果：" + yfscreenshotProcessId + "|" + yfscreenshotWinId);
    }catch(e){
        console.error('getScreenshotPidWinId error', e);
    }
}

function yfscreenshotBegin(){
    // 截图前先确认截图工具是否已启动
    getScreenshotPidWinId();
    if(yfscreenshotWinId != 0 && yfscreenshotProcessId != 0){
        // if(yfscreenshotProcessId == yfscreenshotProcessId_ImStart && yfscreenshotWinId == yfscreenshotWinId_ImStart){
        // 当有钉在桌面的截图时，yfscreenshotProcessId相同，但获取的yfscreenshotWinId可能不同（会获取到钉在桌面的截图的窗口），所以此处不能对yfscreenshotWinId判断，只要保证yfscreenshotProcessId相同就可以
        if(yfscreenshotProcessId == yfscreenshotProcessId_ImStart){
            // 则确定此为由当前IM启动的工具
            isScreenshotRestartRequired = false;
            // 截图工具启动中则直接执行截图
            // var sendResult = require("./SendWindowsMsg").User32SendMsg(yfscreenshotWinId, WM_USER_SCREENSHOT_START);
            // 当有钉在桌面的截图时，需要使用最初启动时的yfscreenshotWinId_ImStart
            var sendResult = require("./SendWindowsMsg").User32SendMsg(yfscreenshotWinId_ImStart, WM_USER_SCREENSHOT_START);
            console.log("**********************接执行截图sendResult: " + sendResult);
        }else{
            // 可能是手动kill掉IM启动的工具后，手动启动了工具，需要kill掉再重启截图工具
            console.log("**********************kill已启动的截图工具前2: " + yfscreenshotProcessId + "|" + yfscreenshotWinId);
            console.log("**********************kill已启动的截图工具前2_ImStart: " + yfscreenshotProcessId_ImStart + "|" + yfscreenshotWinId_ImStart);
            // 在主进程启动时会check并kill一次，在login时再check+kill时可能processId还不为0，但winId已经为0，所以再次kill会报错，经判断无影响
            killYfScreenshotProcess();
            yfscreenshotWinId = 0;
            yfscreenshotProcessId = 0;
            yfscreenshotWinId_ImStart = 0;
            yfscreenshotProcessId_ImStart = 0;
            console.log("**********************kill已启动的截图工具后2: " + yfscreenshotProcessId + "|" + yfscreenshotWinId);
            isScreenshotRestartRequired = true;
            yfscreenshotStartup();
        }
    }else{
        // 可能手动kill掉了工具，需要重启
        yfscreenshotWinId = 0;
        yfscreenshotProcessId = 0;
        yfscreenshotWinId_ImStart = 0;
        yfscreenshotProcessId_ImStart = 0;
        isScreenshotRestartRequired = true;
        yfscreenshotStartup();
    }
}

function yfscreenshotStartup(){
    // 启动QT截图工具yfscreenshot，启动后截图工具会发送WM_USER_SCREENSHOT_WINID消息
    var screenshortPath = getYfScreenshortAppPath();
    screenshortPath += ' ' + yfxIMWinId.toString();
    yfscreenshotProcess = exec(screenshortPath);
}

function killYfScreenshotProcess(){
    // 杀掉QT截图工具yfscreenshot进程
    console.log("============ QT截图工具yfscreenshot进程kill开始:" + yfscreenshotProcessId);
    exec("tskill " + yfscreenshotProcessId, function (err){
        if (err){
            console.log("============ QT截图工具yfscreenshot进程kill ERROR:" + err);
        }else{
            console.log("yfscreenshotProcessId(" + yfscreenshotProcessId +") Kill SUCCESS");
        }
    });
};

function exitApp(isQuitAndInstall=false, isDelta=false){
    // mainWindow.hide(); // 系统托盘退出时会短暂呈现拉宽的登录页面，需点击退出时直接隐藏掉
    forceQuit = true;
    console.log("$$$$ exitApp forceQuit: " + forceQuit);
    mainWindow = null;
    proto.disconnect(0);
    console.log('--------------- disconnect', proto);
    // var now = new Date();
    // var exitTime = now.getTime() + 1000;
    // while (true) {
    //     now = new Date();
    //     if (now.getTime() > exitTime)
    //         break;
    // }
    // app.exit(0);
    setTimeout(() => {
        if(!isQuitAndInstall){
            app.exit(0);
        }else{
            // autoUpdater.quitAndInstall();
            // deltaUpdater.quitAndInstall();
            if(isDelta){
                app.exit(0);
            }else{
                autoUpdater.quitAndInstall();
            }
        }
    }, 1000);
}

function updateTray(unread = 0) {
    settings.showOnTray = true;
    // linux 系统不支持 tray
    if (process.platform === 'linux') {
        return;
    }

    if (settings.showOnTray && isLoginFlag === true) {
        if (tray
            && updateTray.lastUnread === unread) {
            return;
        }

        let contextmenu = Menu.buildFromTemplate(trayMenu);
        // let contextmenuWithLogout = Menu.buildFromTemplate(trayMenuWithLogout);

        let icon;
        if (!isOsx) {
            icon = `${workingDir}/images/icon.png`;
        } else {
            icon = `${workingDir}/images/icon.png`;
        }

        // Make sure the last tray has been destroyed
        setTimeout(() => {
            if (!tray || tray.isDestroyed()) {
                // Init tray icon
                tray = new Tray(icon);
                if (process.platform === 'linux') {
                    tray.setContextMenu(contextmenu);
                }
                tray.on('right-click', () => {
                    newMessageNoticeWin.hide();
                    tray.popUpContextMenu(contextmenu);
                    // if (isLoginFlag === true){
                    //     tray.popUpContextMenu(contextmenu);
                    // } 
                    // else {
                    //     tray.popUpContextMenu(contextmenuWithLogout);
                    // }
                });

                tray.on('click', () => {
                    newMessageNoticeWin.hide();
                    showMainWindow();
                });
                tray.on('double-click', () => {
                    // TODO 遍历有未读消息的会话打开
                    mainWindow.webContents.send('on-tray-double-click', "");
                    newMessageNoticeWin.hide();
                    showMainWindow();
                  });
                // 鼠标移动 TODO
                tray.on('mouse-move', () => {
                    if (isLeave) {
                        // 触发mouse-enter
                        // 下面逻辑有地方不能及时设置为true，会导致newMessageNoticeWin不显示，此处暂且注掉
                        // isLeave = false;
                        console.log( GetNowDateTime() + " mouse-move 触发mouse-enter " + isLoginFlag);
                        if (isLoginFlag === true && isTrayBlink){
                            // 设置窗口位置
                            SetNewMessageNoticePosition(newMessageNoticeWin);
                            newMessageNoticeWin.show();
                            checkTrayLeave();
                        }
                    }
                });

                // 使用Notification表示消息下面方法暂时取消
                // tray.on('balloon-show', () => {
                //     console.info("updateTray setTimeout balloon-show");
                // });
                // tray.on('balloon-click', () => {
                //     console.info("updateTray setTimeout balloon-click");
                //     if (!mainWindow.isVisible() || mainWindow.isMinimized()) {
                //         mainWindow.show();
                //         mainWindow.focus();
                //     }
                // });
            }

            if (isOsx) {
                tray.setTitle(unread > 0 ? ' ' + unread : '');
            } else {
                tray.setTitle('');
            }

            tray.setImage(icon);
            execBlink(unread > 0);
            // Avoid tray icon been recreate
            updateTray.lastUnread = unread;
            // 鼠标放在托盘上显示tooltip
            tray.setToolTip('翼丰信');
        });
    } else {
        if (!tray || tray.isDestroyed()) {
            // nothing
        }else{
            tray.destroy();
        }
        // if (!tray) return;
        //
        // // if (!isOsx) {
        // tray.destroy();
        // // }
        tray = null;
    }
}
function GetNowDateTime(){
    let now = new Date();
    return now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "." + now.getMilliseconds();
}

function SetNewMessageNoticePosition(win, offset = 0){
    if(win == null || win == undefined || win.isDestroyed() || !tray || tray.isDestroyed()){
        return;
    }
    var windowBrow = screen.getPrimaryDisplay();
    var workAreaSize = windowBrow["workAreaSize"];
    var workArea = windowBrow["workArea"];
    var windowSize = windowBrow["size"];
    // var scaleFactor = windowBrow.scaleFactor;
    var tempTrayBounds = tray.getBounds();
    // 此处取到的windowSize就是缩放后的值，不需要根据缩放比再计算
    // console.log('当前pc缩放比例为 scaleFactor: ' + scaleFactor);
    const currentBrowser = win.getBounds();
    // 此处取到的currentBrowser就是缩放后的值，不需要根据缩放比再计算
    // let cursor = screen.getCursorScreenPoint();
    // 以下cursor值和robotjs取的鼠标位置值一样，所以cursor取到的就是缩放后的值，可直接使用，不需要单独传入
    // console.log('当前屏幕宽/高: ' + windowSize.width + '|' + windowSize.height);
    // console.log('当前屏幕工作区域宽/高: ' + workAreaSize.width + '|' + workAreaSize.height);
    // console.log('当前光标位置cursor: ' + cursor.x + '|' + cursor.y);
    // console.log('窗口宽/高: ' + currentBrowser.width + '|' + currentBrowser.height);
    // console.log('托盘参数: width:' + tempTrayBounds.width + '|height:' + tempTrayBounds.height + '|x:' +tempTrayBounds.x + '|y:' + tempTrayBounds.y);
    // console.log('工作区域(x,y): (' + workArea.x + ',' + workArea.y  + '),(宽/高): ' + workArea.width + '|' + workArea.height);

    let halfWidth = currentBrowser.width / 2;
    let halfHeight = currentBrowser.height / 2;
    let currentTrayCentWidth = tempTrayBounds.x + tempTrayBounds.width/2;
    let currentTrayCentHeight = tempTrayBounds.y + tempTrayBounds.height/2;
    // console.log('托盘中心: width:' + currentTrayCentWidth + '|height:' + currentTrayCentHeight);
    let winX = 0;
    let winY = 0;
    if(isDevelopment){
        // console.log('======窗口是否打开' + win.isVisible());
    }
    if (win.isVisible()) {
        var position = win.getPosition();
        if(isDevelopment){
            // console.log('======窗口位置X/Y: ' + position.x + '/' + position.y);
            // console.log('======任务栏方位 : ' + taskbarOrientation);
        }
        winX = position[0];
        winY = position[1];
        if (taskbarOrientation === 1) {
            // 任务栏在下
            winY = winY - offset;
        } else if (taskbarOrientation === 2) {
            // 任务栏在上部

        } else if (taskbarOrientation === 3) {
            // 任务栏在右
            winY = winY - offset / 2;
        } else if (taskbarOrientation === 4) {
            // 任务栏在左
            winY = winY - offset / 2;
        }
    } else {
        if (workAreaSize.width === windowSize.width && workAreaSize.height < windowSize.height) {
            winX = currentTrayCentWidth - halfWidth;
            if (workArea.y === 0) {
                // console.log('任务栏位置：下');
                taskbarOrientation = 1;
                // 任务栏在下
                winY = workAreaSize.height - currentBrowser.height;
            } else {
                // console.log('任务栏位置：上');
                taskbarOrientation = 2;
                // 任务栏在上部
                winY = windowSize.height - workAreaSize.height;
            }
        } else {
            if (workArea.x === 0) {
                // console.log('任务栏位置：右');
                taskbarOrientation = 3;
                // 任务栏在右
                winX = workAreaSize.width - currentBrowser.width;
            } else {
                // console.log('任务栏位置：左');
                taskbarOrientation = 4;
                // 任务栏在左
                winX = windowSize.width - workAreaSize.width;
            }
            winY = currentTrayCentHeight - halfHeight;
            if (winY + currentBrowser.height > workAreaSize.height) {
                winY = workAreaSize.height - currentBrowser.height - 10;
            }
        }
    }
    // console.log('新消息窗口位置（X|Y）: ' + winX + '|' + winY);
    winX = Math.floor(winX);
    winY = Math.floor(winY);
    // console.log('新消息窗口位置New（X|Y）: ' + winX + '|' + winY);
    win.setPosition(winX, winY);
}

function checkTrayLeave() {
    // leaveInter && clearInterval(leaveInter);
    if(!!leaveInter || leaveInter != null){
        clearInterval(leaveInter);
        console.log("------------------checkTrayLeave_1 clearInterval(leaveInter): ", leaveInter);
        leaveInter = null;
        console.log("------------------checkTrayLeave_1 leaveInter = null: ", leaveInter);
    }
    if (!tray || tray.isDestroyed() || !newMessageNoticeWin.isVisible()){
        isLeave = true;
        isNoticeWinLeave = true;
        return;
    }
    leaveInter = setInterval(function () {
        if (!tray || tray.isDestroyed()){
            // leaveInter && clearInterval(leaveInter);
            if(!!leaveInter || leaveInter != null){
                clearInterval(leaveInter);
                console.log("------------------checkTrayLeave_2 clearInterval(leaveInter): ", leaveInter);
                leaveInter = null;
                console.log("------------------checkTrayLeave_2 leaveInter = null: ", leaveInter);
            }
            isLeave = true;
        }else{
            trayBounds = tray.getBounds();
            point = screen.getCursorScreenPoint();
            if (!(trayBounds.x < point.x && trayBounds.y < point.y && point.x < (trayBounds.x + trayBounds.width) && point.y < (trayBounds.y + trayBounds.height))) {
                //触发mouse-leave
                console.info(GetNowDateTime() + " mouse-move 触发mouse-leave");
                if (isLoginFlag === true) {
                    // 判断光标是否移出消息提示窗口
                    focusIntoWindow(newMessageNoticeWin, point);
                    if (isNoticeWinLeave) { // 离开的时候
                        newMessageNoticeWin.hide();
                        // leaveInter && clearInterval(leaveInter);
                        if(!!leaveInter || leaveInter != null){
                            clearInterval(leaveInter);
                            console.log("------------------checkTrayLeave_3 clearInterval(leaveInter): ", leaveInter);
                            leaveInter = null;
                            console.log("------------------checkTrayLeave_3 leaveInter = null: ", leaveInter);
                        }
                        isLeave = true;
                    }
                } else {
                    // leaveInter && clearInterval(leaveInter);
                    if(!!leaveInter || leaveInter != null){
                        clearInterval(leaveInter);
                        console.log("------------------checkTrayLeave_4 clearInterval(leaveInter): ", leaveInter);
                        leaveInter = null;
                        console.log("------------------checkTrayLeave_4 leaveInter = null: ", leaveInter);
                    }
                    isLeave = true;
                }
            }
        }
    }, 100);
}

function focusIntoWindow(win, point) {
    if (win == null || win == undefined || win.isVisible() == false || win.isDestroyed()) {
        isNoticeWinLeave = true;
    } else {
        noticeWinBounds = win.getBounds();
        // noticeWinPoint = screen.getCursorScreenPoint();
        if (!(noticeWinBounds.x < point.x && noticeWinBounds.y < point.y && point.x < (noticeWinBounds.x + noticeWinBounds.width) && point.y < (noticeWinBounds.y + noticeWinBounds.height))) {
            //触发mouse-leave（focusIntoWindow focus Out）
            // console.info(GetNowDateTime() + " focusIntoWindow 触发mouse-leave");
            isNoticeWinLeave = true;
        } else {
            //触发mouse-leave（focusIntoWindow focus enter）
            // console.info(GetNowDateTime() + " focusIntoWindow 触发mouse-enter");
            isNoticeWinLeave = false;
        }
    }
}

function createMenu() {
    // var menu = Menu.buildFromTemplate(mainMenu);
    var menu = Menu.buildFromTemplate(mainMenu2);
    console.log("isOsx:" + isOsx)
    if (isOsx) {
        Menu.setApplicationMenu(menu);
    } else {
        // mainWindow.setMenu(null);
        // 隐藏浏览器的子弹窗中左上角的menubar，父层可在创建BrowserWindow时隐藏，子窗口只能在此隐藏
        // Menu.setApplicationMenu(null);
        Menu.setApplicationMenu(menu);
    }
}

function regShortcut() {
    // if(isWin) {
    globalShortcut.register('CommandOrControl+G', () => {
        mainWindow.webContents.toggleDevTools();
    })
    // }
}

const downloadHandler = (event, item, webContents) => {
    // 设置保存路径,使Electron不提示保存对话框。
    // item.setSavePath('/tmp/save.pdf')
    let pdfURL = item.getURL();
    console.log('%%%%%%%%%当前文件的url: ' + pdfURL);
    if(pdfURL.indexOf("LR_OAModule/ResourceFile/PreviewFile?fileId") != -1){
        // item.setSavePath('/tmp/save.pdf');
        // var savedHere = item.getSavePath();
        pdfPreviewWindow = new BrowserWindow({
            width: 800,
            height: 600,
            icon:`${workingDir}/favicon.ico`,
            webPreferences: {
                nodeIntegration: false,
                contextIsolation: false,
                webSecurity: false,
            },
        });
        const param = qs.stringify({file: pdfURL});
        // pdfWindow.loadURL(path.resolve("file://", savedHere));
        pdfPreviewWindow.loadURL('file://' + workingDir + '/pdfjs/web/viewer.html?' + param);
        // require("@electron/remote/main").enable(pdfPreviewWindow.webContents);
        remoteMainEnable(pdfPreviewWindow.webContents);
        // pdfPreviewWindow.webContents.openDevTools();
        // 不需要以下事件，否则会报错
        // pdfWindow.on('close', ()=>{
        //     pdfWindow = null;
        //     mainWindow.focus();
        // });
        // pdfWindow.show();
        // shell.openExternal(pdfURL);
        // 禁止后续处理执行（比如下载弹窗，但oa的iframe预览弹窗无法禁止），electron10以后可实现直接在oa中预览
        // https://www.electronjs.org/docs/latest/api/session
        event.preventDefault();
        return;
    }
    let file = downloadFileMap.get(item.getURL());
    let fileName = "";
    if(file == null || file == undefined){
        // oa中很多文件下载页面，不能一一列举（比如组织架构图的保存(pdf或png[base64])，无法判断具体url，此判断条件暂且删除）
        // if(pdfURL.indexOf("LR_OAModule/ResourceFile/DownloadFile") != -1 || pdfURL.indexOf("LR_SystemModule/Annexes/DownAnnexesFile") != -1){
            // 如果是oa文件管理的下载，则允许弹窗，但禁止后续处理
            // item.setSaveDialogOptions({ title: '保存文件' });
            console.log('Download file null or undefined return!!')
            fileName = item.getFilename();
            console.log('item.getFileName(): ' + fileName)
            // return;
        // }
        // 目前从webview过来的下载除了工作台，还有浏览器，在此判断是否为浏览器的媒体另存，如果是则忽略，否则会弹出两次另存弹窗（以下无法拦截）
        // console.log("BrowserWindow.fromWebContents(webContents).webContents.id: " + BrowserWindow.fromWebContents(webContents).webContents.id);
        // console.log("webBrowserWindow.webContents.id: " + webBrowserWindow.webContents.id);
        // if(BrowserWindow.fromWebContents(webContents).webContents.id == webBrowserWindow.webContents.id){
        //     // event.preventDefault();
        //     return;
        // }
    }else{
        fileName = file.fileName;
    }
    item.setSaveDialogOptions({ title: '保存文件', defaultPath: fileName });

    // 通知浏览器关闭下载时弹出的空页面（tab）
    if(!!webBrowserWindow && !!BrowserWindow.fromWebContents(webContents) && BrowserWindow.fromWebContents(webContents).webContents.id == webBrowserWindow.webContents.id){
        var pageUrl = webContents.getURL();
        console.log("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& pageUrl: " + pageUrl);
        // 下载时downloadHandler中为跳转后的结果，已经获取不到currentTab.url，如果webcontents.getURL为空则删除当前tab
        if(!pageUrl){
            webBrowserWindow.webContents.send('closeDownloadTab', {url: pageUrl});
        }
    }

    item.on('updated', (event, state) => {
        try {
            if (state === 'interrupted') {
                console.log('Download is interrupted but can be resumed');
            } else if (state === 'progressing') {
                if (item.isPaused()) {
                    console.log('Download is paused')
                } else {
                    console.log(`Received bytes: ${fileName} ${item.getReceivedBytes()}, ${item.getTotalBytes()}`)
                    let downloadFile = downloadFileMap.get(item.getURL());
                    // 来自工作台的下载downloadFile为undefined，messageId为空
                    let messageId = downloadFile == undefined? '' : downloadFile.messageId;
                    let args = {
                        messageId: messageId,
                        receivedBytes: item.getReceivedBytes(),
                        totalBytes: item.getTotalBytes(),
                        isAlertView: (file == null || file == undefined)? '' : file.isAlertView,
                        alertMessageId: (file == null || file == undefined)? '' : file.messageContentId,
                        alertMessage: (file == null || file == undefined)? '' : file.alertMessage,
                        messageType: (file == null || file == undefined)? '' : file.messageType,
                    }
                    webContents.send('file-download-progress', args);
                }
            }

        } catch (e) {
            console.log('downloadHandler updated error', e)
        }
    })
    item.once('done', (event, state) => {
        try {
            let downloadFile = downloadFileMap.get(item.getURL());
            if (!downloadFile) {
                if(!!workspaceWindow){
                    if(webContents.id == workspaceWindow.webContents.id){
                        // 来自工作台的下载downloadFile为undefined，messageId为空
                    }else{
                        console.log('Download done return - 1 !!')
                        return;
                    }
                }else{
                    console.log('Download done return - 2 !!')
                    return;
                }
            }
            let messageId = downloadFile == undefined? '' : downloadFile.messageId;
            console.log(state)
            if (state === 'completed') {
                console.log('Download successfully')
                let isFromWorkspace = false;
                if(!!workspaceWindow){
                    // 工作台html2pdf已成功
                    if(webContents.id == workspaceWindow.webContents.id){
                        isFromWorkspace = true;
                        webContents.send('workspace-html2pdf-success', {});
                    }
                }
                if(!isFromWorkspace){
                    webContents.send('file-downloaded', {
                        messageId: messageId, filePath: item.getSavePath(), isAlertView: downloadFile == undefined? '' : downloadFile.isAlertView, alertMessageId: downloadFile == undefined? '' : downloadFile.alertMessageId,
                        alertMessage: downloadFile == undefined? '' : downloadFile.alertMessage,messageType:downloadFile.messageType,
                    });
                }
            } else if(state === 'cancelled'){
                let isFromWorkspace = false;
                if(!!workspaceWindow){
                    // 工作台html2pdf已取消
                    if(webContents.id == workspaceWindow.webContents.id){
                        isFromWorkspace = true;
                        webContents.send('workspace-html2pdf-cancel', {});
                    }
                }
                //每次取消下载 state 都进这个分支  导致取消下载时  页面无法还原  写法待确认
                if(!isFromWorkspace){
                    webContents.send('file-download-failed', {
                        messageId: messageId, state: state, isAlertView: downloadFile == undefined? '' : downloadFile.isAlertView, alertMessageId: downloadFile == undefined? '' : downloadFile.alertMessageId,
                        alertMessage: downloadFile == undefined? '' : downloadFile.alertMessage ,messageType:downloadFile.messageType,
                    });
                }
            } else {
                let isFromWorkspace = false;
                if(!!workspaceWindow){
                    // 工作台html2pdf已失败
                    if(webContents.id == workspaceWindow.webContents.id){
                        isFromWorkspace = true;
                        webContents.send('workspace-html2pdf-failed', {});
                    }
                }
                if(!isFromWorkspace){
                    webContents.send('file-download-failed', {
                        messageId: messageId, state: state, isAlertView: downloadFile == undefined? '' : downloadFile.isAlertView, alertMessageId: downloadFile == undefined? '' : downloadFile.alertMessageId,
                        alertMessage: downloadFile == undefined? '' : downloadFile.alertMessage ,messageType:downloadFile.messageType,
                    });
                }
                console.log(`Download failed: ${state}`)
            }
            downloadFileMap.delete(item.getURL());

        } catch (e) {
            console.log('downloadHandler done error', e)
        }
    })
}

const createMainWindow = async () => {
    let mainWindowState = windowStateKeeper({
        defaultWidth: 1080,
        defaultHeight: 720,
    });

    mainWindow = new BrowserWindow({
        x: mainWindowState.x,
        y: mainWindowState.y,
        width: 700,
        height: 500,
        minWidth: 700,
        minHeight: 500,
        frame: false,
        backgroundColor: '#00000000',
        transparent: true,
        titleBarStyle: 'hidden',
        maximizable: false,
        pinable: false,
        pin_title: '置顶',
        resizable: false,
        useContentSize: true,
        movable: true,
        icon:`${workingDir}/favicon.ico`,
        // 以下两属性设置时会导致win不能正常unmaximize. electron bug
        // transparent: true,
        // resizable: false,
        webPreferences: {
            scrollBounce: false,
            nodeIntegration: true,
            contextIsolation: false,
            nativeWindowOpen: true,
            webSecurity: false,
            navigateOnDragDrop: true,
            // 窗口间共享indexeddb等，但不设置貌似也好用
            // partition: 'persist:default',
        },
    });
    mainWindow.center();
    const badgeOptions = {}
    new Badge(mainWindow, badgeOptions);

    mainWindow.once('focus',()=>mainWindow.flashFrame(false));
    // require("@electron/remote/main").enable(mainWindow.webContents);
    remoteMainEnable(mainWindow.webContents);
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        console.log("/*//***********************/" + process.env.WEBPACK_DEV_SERVER_URL);
        await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        mainWindow.webContents.openDevTools()
        // if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
    } else {
        createProtocol('app')
        // Load the index.html when not in development
        mainWindow.loadURL('app://./index.html')
    }

    // console.log("------------------------------------------process.env.DISABLE_V8_COMPILE_CACHE设置前：" + process.env.DISABLE_V8_COMPILE_CACHE);
    // // disable the cache and use v8-compile-cache
    // // https://github.com/zertosh/v8-compile-cache?spm=taofed.bloginfo.blog.15.300d5ac8WotiOx
    // process.env.DISABLE_V8_COMPILE_CACHE = 0;
    // console.log("------------------------------------------process.env.DISABLE_V8_COMPILE_CACHE设置后：" + process.env.DISABLE_V8_COMPILE_CACHE);
    // console.log("------------------------------------------process.env.DISABLE_V8_COMPILE_CACHE设置后：" + !process.env.DISABLE_V8_COMPILE_CACHE);
    // require('v8-compile-cache');
    // var test = require('v8-compile-cache').__TEST__;
    // var cachedir = test.getCacheDir;
    // var supportsCached = test.supportsCachedData;
    // var getMainName = test.getMainName;
    // console.log("------------------------------------------getCacheDir：" + cachedir());
    // console.log("------------------------------------------supportsCached：" + supportsCached());
    // console.log("------------------------------------------getMainName" + getMainName());

    // const WM_DROPFILES = 0x0233;
    // mainWindow.hookWindowMessage(WM_DROPFILES, (wParam, lParam) => {
    //     const event = wParam.readUInt32LE(0);
    //     console.log("----------------------------------------------------------get WM_DROPFILES message: " + event);
    //     mainWindow.webContents.send('dropFilesComeFromWindows', {});
    // });

    // // 接收windows消息，可监听mainwindow是否被激活（event为0时：激活->未激活，1时->未激活->激活）
    // const WM_ACTIVATEAPP = 0x001C;
    // mainWindow.hookWindowMessage(WM_ACTIVATEAPP, (wParam, lParam) => {
    //     const event = wParam.readUInt32LE(0);
    //     let msg = event == 1? "翼丰信已激活" : "翼丰信未激活";
    //     console.log("----------------------------------------------------------get WM_ACTIVATEAPP message: " + msg);
    // });

    // 屏蔽系统右键菜单
    DisableRightClickContextMenu(mainWindow);

    mainWindow.webContents.on('did-finish-load', (e) => {
        try {
            // 设置win10窗体模糊效果
            // electronVibrancy.enableVibrancy(mainWindow);
            // 设置透明窗体（transparent=true）事件补丁
            plugin({
                browserWindow: mainWindow,
            });
            mainWindow.show();
            mainWindow.focus();
            setTimeout(() => mainWindow.setOpacity(1), 1000 / 60);
            // 启动时检测是否有更新
            setTimeout(()=>{
                // 确保在主窗口显示以后显示
                // autoUpdater.checkForUpdates();
                deltaUpdater.checkForUpdates();
            }, 50);
            // 测试crashReport用
            // process.crash();
        } catch (ex) {
            // do nothing
        }
    });
}

app.on('ready', async () => {
    // 输出net log
    let date = new Date();
    date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
    let netLogPath = "";
    if (process.env.WEBPACK_DEV_SERVER_URL){
        netLogPath =  __dirname + '\\logs\\' + date + '-net.log';
    }else{
        let userData = app.getPath('userData');
        netLogPath = `${userData}\\logs\\` + date + '-net.log';
    }
    let options = {
        captureMode: 'includeSensitive',
        maxFileSize: 10485760, // 10M
    };
    netLog.startLogging(netLogPath, options);

    initProtoMain(proto);
    
    createMainWindow();
    registerLocalResourceProtocol();
    registerBdapiProtocol();
    // app.setName(pkg.name);
    app.setName(pkg_name_cn);
    // if (process.platform === 'win32') {
    //     app.setAppUserModelId("翼丰信");
    // }

    if (process.platform === 'win32') {
        // 默认情况下，Electron 应用程序可能不会自动适应高 DPI 屏幕，导致应用程序在高 DPI 屏幕上显示模糊或缩放不正确
        // 此语句启用高 DPI 支持可能会对应用程序的布局和界面进行一些调整，以适应高 DPI 屏幕，参数为0时关闭此功能
        app.commandLine.appendSwitch('high-dpi-support', 1);
        // 设备缩放因子是指将物理像素和逻辑像素之间的映射比例。在高 DPI 屏幕上，操作系统通常会自动应用缩放因子，以确保应用程序在高 DPI 屏幕上以适当的尺寸和比例显示
        // 强制设置设备缩放因子为 1，即取消自动缩放。这意味着应用程序将以物理像素的实际大小进行显示，而不考虑高 DPI 屏幕的缩放设置
        // app.commandLine.appendSwitch('force-device-scale-factor', 1);
    }

    app.setUserTasks([]);
    session.defaultSession.webRequest.onBeforeSendHeaders(
        (details, callback) => {
            // 可根据实际需求，配置 Origin，默认置为空
            // details.requestHeaders.Origin = '';
            callback({cancel: false, requestHeaders: details.requestHeaders});
        }
    );
    // 20220323 DEL
    // try {
    //     updateTray()
    // } catch (e) {
    //     // do nothing
    // }
    try {
        await deltaUpdater.boot({
            showNotification: false
        });
      } catch (error) {
        logger.error(error);
      }
});

// app.on('window-all-closed', () => {
//     if (process.platform !== 'darwin') {
//         app.quit()
//     }
// })

app.on('before-quit', () => {
    // Fix issues #14
    forceQuit = true;
    console.log("---------------$$$$ before-quit forceQuit: " + forceQuit);

    if (!tray || tray.isDestroyed()) {
        // nothing
        return;
    }else{
        tray.destroy();
        tray = null;
        console.log("before-quit ****tray has distroyed!!!");
    }

});
app.on('activate', e => {
    if (!mainWindow.isVisible()) {
        mainWindow.show();
    }
});



function showMainWindow(args){
    if (!mainWindow.isVisible()) {
        // hide后的mainwindow显示时需要settimeout，否则会冻住，只有点击其它窗体或移动一下才能恢复
        setTimeout(()=>{
            mainWindow.webContents.send('newMessageNotice-readConversation-main', args);
            console.log('托盘已读事件 newMessageNotice-readConversation end');
            // 如果在hide前不加minimize，此处也不需要restore了
            // mainWindow.restore();
            mainWindow.show();
        }, 50);
    } else if (mainWindow.isMinimized()) {
        mainWindow.restore();
        mainWindow.show();
    }else{
        mainWindow.show();
    }
    // mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
}

// 发送消息给setting画面
function sendStatusToSettingWindow(status, params) {
    moadlBrowserWindow && moadlBrowserWindow.webContents.send(status, params);
}
// 发送消息给main画面
function sendStatusToMinWindow(status, params) {
    if(isLoginFlag){
        mainWindow && mainWindow.webContents.send(status + "-home", params);
    }else{
        mainWindow && mainWindow.webContents.send(status + "-login", params);
    }
}

// autoUpdater.on('checking-for-update', () => {
//     if(!moadlBrowserWindow || moadlBrowserWindow == null){
//         // 启动时的更新
//         sendStatusToMinWindow('Checking for update...');
//     }else{
//         // setting页面更新
//         sendStatusToSettingWindow('Checking for update...');
//     }
// });
deltaUpdater.on('checking-for-update', () => {
    if(!moadlBrowserWindow || moadlBrowserWindow == null){
        // 启动时的更新
        sendStatusToMinWindow('Checking for update...');
    }else{
        // setting页面更新
        sendStatusToSettingWindow('Checking for update...');
    }
});
// autoUpdater.on('update-available', (info) => {
//     // 可以更新版本
//     let content = process.platform === 'win32' ? info.releaseNotes : info.releaseName;
//     const dialogOpts = {
//         type: 'info',
//         buttons: ['立即下载','稍后'],
//         title: '翼丰信版本更新',
//         textWidth: 250,
//         message: '发现新版本：v'+info.version+"("+(info.files[0].size/1024/1024).toFixed(2)+"MB)"+"\r\n\r\n" + (!!content? content : ""),
//         detail: '是否立即下载？',
//         cancelId: 1, // 按esc默认点击取消按钮
//         defaultId: 0, // 默认高亮的按钮下标，回车的时候自动选中该项
//     };
//     if(!moadlBrowserWindow || moadlBrowserWindow == null){
//         // 启动/已登录时的更新
//         sendStatusToMinWindow('autoUpdater-canUpdate', dialogOpts);
//         // dialog.showMessageBox(dialogOpts).then((returnValue) => {
//         //     if (returnValue.response ===0) {
//         //         console.log('开始下载更新');
//         //         autoUpdater.downloadUpdate();
//         //     }else{
//         //         console.log('取消下载更新');
//         //         return;
//         //     }
//         // });
//     }else{
//         // setting页面的更新
//         sendStatusToSettingWindow('autoUpdater-canUpdate', dialogOpts);
//     }
// });
deltaUpdater.on('update-available', (info) => {
    console.log("++++++++++++++++++++++++ update-available start!!");
    // console.log(info);
    // 可以更新版本
    // let content = process.platform === 'win32' ? info.releaseNotes : info.releaseName;
    const dialogOpts = {
        type: 'info',
        buttons: ['立即下载','稍后'],
        title: '翼丰信版本更新',
        textWidth: 250,
        // message: '发现新版本：v'+info.version+"("+(info.files[0].size/1024/1024).toFixed(2)+"MB)"+"\r\n\r\n" + (!!content? content : ""),
        message: '发现新版本：v'+info.version+"("+(info.files[0].size/1024/1024).toFixed(2)+"MB)",
        detail: '是否立即下载？',
        latestReleaseInfo: info.latestReleaseInfo,
        releaseNotes: info.releaseNotes,
        cancelId: 1, // 按esc默认点击取消按钮
        defaultId: 0, // 默认高亮的按钮下标，回车的时候自动选中该项
        forceUpdate: info.forceUpdate, // 添加是否强制更新，强制时隐藏取消和关闭按钮
    };
    if(!moadlBrowserWindow || moadlBrowserWindow == null){
        // 启动/已登录时的更新
        sendStatusToMinWindow('autoUpdater-canUpdate', dialogOpts);
    }else{
        // setting页面的更新
        sendStatusToSettingWindow('autoUpdater-canUpdate', dialogOpts);
    }
});
// autoUpdater.on('update-not-available', (info) => {
//     // 无可用更新
//     sendStatusToSettingWindow('autoUpdater-noUpdate', info);
//   });
deltaUpdater.on('update-not-available', (info) => {
    // 无可用更新
    if(!moadlBrowserWindow || moadlBrowserWindow == null){
        // 启动时的更新
        sendStatusToMinWindow('autoUpdater-noUpdate', info);
    }else{
        // setting页面更新
        sendStatusToSettingWindow('autoUpdater-noUpdate', info);
    }
  });
// autoUpdater.on('error', (err) => {
//     // 更新错误
//     if(!moadlBrowserWindow || moadlBrowserWindow == null){
//         // 启动时的更新
//         sendStatusToMinWindow('autoUpdater-error', err);
//     }else{
//         // setting页面更新
//         sendStatusToSettingWindow('autoUpdater-error', err);
//     }
// });
deltaUpdater.on('error', (err) => {
    // 更新错误
    if(!moadlBrowserWindow || moadlBrowserWindow == null){
        // 启动时的更新
        sendStatusToMinWindow('autoUpdater-error', err);
    }else{
        // setting页面更新
        sendStatusToSettingWindow('autoUpdater-error', err);
    }
});
// 发起更新程序
// ipcMain.on('autoUpdater-toDownload', () => {
//     autoUpdater.downloadUpdate();
// });
ipcMain.on('autoUpdater-toDownload', () => {
    // autoUpdater.downloadUpdate();
    deltaUpdater.downloadUpdate();
});
// autoUpdater.on('download-progress', (progressObj) => {
//     // 正在下载的下载进度
//     if(!moadlBrowserWindow || moadlBrowserWindow == null){
//         // 启动时的更新
//         sendStatusToMinWindow('autoUpdater-progress', progressObj);
//     }else{
//         // setting页面更新
//         sendStatusToSettingWindow('autoUpdater-progress', progressObj);
//     }
// });
deltaUpdater.on('download-progress', (progressObj) => {
    // 正在下载的下载进度
    if(!moadlBrowserWindow || moadlBrowserWindow == null){
        // 启动时的更新
        sendStatusToMinWindow('autoUpdater-progress', progressObj);
    }else{
        // setting页面更新
        sendStatusToSettingWindow('autoUpdater-progress', progressObj);
    }
});
// autoUpdater.on('update-downloaded', (ev, releaseNotes, releaseName) => {
//     // 下载完成
//     let content = process.platform === 'win32' ? releaseNotes : releaseName;
//     const options = {
//         type: 'info',
//         buttons: ['确定', '取消'],
//         title: '翼丰信版本更新',
//         message: !!content? content : "",
//         detail: '已完成下载，是否立即安装？',
//         cancelId: 1, // 按esc默认点击取消按钮
//         defaultId: 0, // 默认高亮的按钮下标，回车的时候自动选中该项
//       };
//     if(!moadlBrowserWindow || moadlBrowserWindow == null){
//         // 启动时的更新
//         sendStatusToMinWindow('autoUpdater-downloaded', options);
//         //   dialog.showMessageBox(options).then(returnVal => {
//         //     if (returnVal.response === 0) {
//         //       console.log('开始更新');
//         //       setTimeout(() => {
//         //         autoUpdater.quitAndInstall();
//         //       }, 1000);
//         //     } else {
//         //       console.log('取消更新');
//         //       return;
//         //     }
//         //   });
//     }else{
//         // 设置页面的更新
//         sendStatusToSettingWindow('autoUpdater-downloaded', options);
//     }
// });
deltaUpdater.on('update-downloaded', (info) => {
    console.log("++++++++++++++++++++++++ update-downloaded start!!");
    console.log(info);
    // 下载完成
    // let content = process.platform === 'win32' ? info.releaseNotes : info.releaseName;
    const options = {
        type: 'info',
        buttons: ['确定', '取消'],
        title: '翼丰信版本更新',
        // message: !!content? content : "",
        message: "",
        detail: '已完成下载，是否立即安装？',
        cancelId: 1, // 按esc默认点击取消按钮
        defaultId: 0, // 默认高亮的按钮下标，回车的时候自动选中该项
        forceUpdate: info.forceUpdate, // 添加是否强制更新，强制时隐藏取消和关闭按钮
      };
    if(!moadlBrowserWindow || moadlBrowserWindow == null){
        // 启动时的更新
        sendStatusToMinWindow('autoUpdater-downloaded', options);
    }else{
        // 设置页面的更新
        sendStatusToSettingWindow('autoUpdater-downloaded', options);
    }
});

function clearBlink() {
    if (blink) {
        clearInterval(blink)
        isTrayBlink = false;
    }
    blink = null
}

function execBlink(flag, _interval) {
    let interval = _interval ? _interval : 500;
    let icons;
    icons = [`${workingDir}/images/icon.png`,
    `${workingDir}/images/Remind_icon.png`];

    let count = 0;
    if (flag) {
        if (blink) {
            return;
        }
        blink = setInterval(function () {
            toggleTrayIcon(icons[count++]);
            count = count > 1 ? 0 : 1;
            isTrayBlink = true;
        }, interval);
    } else {
        if (!!newMessageNoticeWin && newMessageNoticeWin.isVisible()){
            newMessageNoticeWin.hide();
        }
        clearBlink();
        toggleTrayIcon(icons[0]);
    }

}

function toggleTrayIcon(icon) {
    if(!!tray && tray.isDestroyed() === false){
        tray.setImage(icon);
    }
}

/**
 * 四舍五入
 * @param  {[type]} num     [待处理数字]
 * @param  {[type]} decimal [需要保留的小数位]
 * @return {[type]} number
 */
function round(num, decimal) {
    if (isNaN(num)) {
        return 0;
    }
    const p1 = Math.pow(10, decimal + 1);
    const p2 = Math.pow(10, decimal);
    return Math.round(num * p1 / 10) / p2;
}
// 文件全路径中获取文件名
function getFileName(fullpath) {
    // var pos = fullpath.lastIndexOf('\\');
    var pos = 0;
    if(fullpath.lastIndexOf('\\') >= 0){
        pos = fullpath.lastIndexOf('\\');
    }else if(fullpath.lastIndexOf('/') >= 0){
        pos = fullpath.lastIndexOf('/');
    }
    return fullpath.substring(pos + 1);
}

// 获取qt截图工具(yfscreenshot.exe)路径
function getYfScreenshortAppPath(){
    if (process.env.WEBPACK_DEV_SERVER_URL){
        const devUrl = '\"' + __dirname + '/yfscreenshot/yfscreenshot.exe' + '\"';
        return devUrl;
    }else{
        var appPath = path.dirname(app.getPath('exe'));
        const eveUrl = '\"' + appPath + '\\resources\\yfscreenshot\\yfscreenshot.exe' + '\"';
        console.log("************yfscreenshot AppPath: " + eveUrl);
        return eveUrl;
    }
}


// 屏蔽系统右键菜单
function DisableRightClickContextMenu(win){
    win.hookWindowMessage(278, () => {
        win.setEnabled(false);
        setTimeout(() => {
            win.setEnabled(true);
        }, 100);
        return true;
    });
}

// 获取windows系统版本
function GetWindowsVersion(){
    try {
        var cmd_result = execSync(`ver`);
        var cmd_result_string = cmd_result.toString();
        console.log("======================= Windows 系统版本: " + cmd_result_string);
        // 命令执行结果：
        // Microsoft Windows [版本 10.0.19044.1706]
        var result_modify = cmd_result_string.split("[")[1];
        var result_modify2 = result_modify.split(" ")[1];
        var verNo = result_modify2.trim().split(".")[0];
        console.log("======================= Windows 系统版本2: " + verNo);
        if(verNo == "10"){
            return "win10";
        }else if(verNo == "6"){
            // win7获取的结果为6.xxx.xxx（同windows server2012）
            // return "win7";
            return "win10";
        }else{
            return "";
        }
    } catch (e) {
        return "";
    }
}